package com.yao.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yao.context.BaseContext;
import com.yao.pojo.Result;
import com.yao.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) return true;
        log.info("拦截路径...{}",request.getRequestURI());

        String jwt = request.getHeader("token");

        if (!StringUtils.hasLength(jwt)) {
            log.info("未登录用户...{}", LocalDateTime.now());

            Result error = Result.error("NOT_LOGIN");
            response.getWriter().write(JSONObject.toJSONString(error));
            response.setStatus(401);

            return false;
        }

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(jwt);

            // 存储用户ID到线程
            Integer userId = (Integer) claims.get("userId");
            BaseContext.setCurrentId(userId);
        } catch (Exception exception) {

            log.info("非法用户...{}", LocalDateTime.now());

//            log.info("具体信息{}", JSONObject.parse(exception.getMessage()));
            System.out.println(exception.getMessage());
            log.error("错误信息,{}",exception.getMessage());
            Result error = Result.error("UNAUTHORIZED_USER");

            response.getWriter().write(JSONObject.toJSONString(error));
            response.setStatus(401);

            return false;
        }
        return true;
    }
}
